package com.example.xinli.job;

import com.example.xinli.domain.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@EnableScheduling
@Component
public class ScheduledTasks {

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(fixedRate = 2500)
    public void reportCurrentTime() {
        // 遍历整个 redis 的 "inter:" + userId 键
        Set<String> keys = redisTemplate.keys("inter:*");
        // System.out.println(keys);
        for (String key : keys) {
            String userId = key.split(":")[1];
            int currProgress = (int) redisTemplate.opsForValue().get(key);
            Long expireTimeSeconds = redisTemplate.getExpire("inter:" + userId, TimeUnit.SECONDS);
            if (expireTimeSeconds != null) {
                // 转换为小时单位
                // 距离过期还有 hoursToExpire 小时
                long hoursToExpire = expireTimeSeconds / 3600;
                WebSocketServer.sendInfo(userId, hoursToExpire + "#" + currProgress);
            }
        }
    }
}
